package main

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

type user struct {
	Id       int    `db:"id"`
	Username string `db:"username"`
	Password string `db:"password"`
}

var db *sqlx.DB // 初始化连接池

func initDB() {
	database, err := sqlx.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/topology")
	if err != nil {
		fmt.Println("open mysql failed,", err)
		return
	}

	db = database
	// defer db.Close() // 注意这行代码要写在上面err判断的下面
}

func find(id int) {
	sqlStr := "select id, username, password from auth_user where id=?"
	var u user
	err := db.Get(&u, sqlStr, id)
	if err != nil {
		fmt.Printf("get failed, err:%v\n", err)
		return
	}
	fmt.Println(u.Id, u.Username, u.Password)
}

func findMuli()  {
	sqlStr := "select id, username, password from auth_user"
	var u []user
	err := db.Select(&u, sqlStr)
	if err != nil {
		fmt.Printf("get failed, err:%v\n", err)
		return
	}
	fmt.Println(len(u))
}

func main() {
	initDB()

	find(1)
	findMuli()

}
